<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Spring原理及应用——Offer来了框架篇第一章, SongX64">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="baidu-site-verification" content="code-8GV6uhDsco" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Spring原理及应用——Offer来了框架篇第一章 | SongX64</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="SongX64" type="application/atom+xml">
</head>



   <style>
    body{
       background-image: url(https://gitee.com/songx86/SongPicBed/raw/master/img/fd039245d688d43f5595595b7d1ed21b0ef43b5f.jpg);
       background-repeat:no-repeat;
       background-size:cover;
       background-attachment:fixed;
    }
</style>



<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">SongX64</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">SongX64</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/blinkfox/hexo-theme-matery" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/blinkfox/hexo-theme-matery" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/1/07.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Spring原理及应用——Offer来了框架篇第一章</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                            <a href="/tags/%E5%90%8E%E7%AB%AF/">
                                <span class="chip bg-color">后端</span>
                            </a>
                        
                            <a href="/tags/Spring/">
                                <span class="chip bg-color">Spring</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%90%8E%E7%AB%AF/" class="post-category">
                                后端
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-08-06
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    6.3k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    23 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="Spring原理及应用"><a href="#Spring原理及应用" class="headerlink" title="Spring原理及应用"></a>Spring原理及应用</h1><p>[TOC]</p>
<h2 id="1-1-Spring特性"><a href="#1-1-Spring特性" class="headerlink" title="1.1 Spring特性"></a>1.1 Spring特性</h2><p>问：Spring有哪些特点？</p>
<p><strong>轻量级、控制反转、面向切面、面向容器、灵活。</strong></p>
<pre class="line-numbers language-mermaid" data-language="mermaid"><code class="language-mermaid"><span class="token keyword">graph</span> TB
Spring特性<span class="token arrow operator">---</span>轻量级
Spring特性<span class="token arrow operator">---</span>控制反转
Spring特性<span class="token arrow operator">---</span>面向容器
Spring特性<span class="token arrow operator">---</span>面向切面
Spring特性<span class="token arrow operator">---</span>灵活
<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<ol>
<li>轻量级<ul>
<li>核心Jar包小</li>
<li>模块化，按需引入</li>
</ul>
</li>
<li>控制反转<ul>
<li>一个对象所<strong>依赖的其他对象</strong>会自动传递给它</li>
<li>实现对象依赖的解耦</li>
</ul>
</li>
<li>面向切面<ul>
<li>提高系统内聚性</li>
<li>抽取公共的业务，只需关注核心业务</li>
</ul>
</li>
<li>面现容器<ul>
<li>实现了对象配置化生成</li>
<li>实现了对象生命周期管理</li>
</ul>
</li>
<li>框架灵活<ul>
<li>对象可以声明式创建</li>
</ul>
</li>
</ol>
<blockquote>
<p>补充：JavaBean</p>
<p>JavaBean是一种Java类，通过<strong>封装属性和方法</strong>成为具有某种功能，或者是处理某个业务的对象。必须有一个<strong>缺省的构造函数</strong>，每个属性都有<strong>get\set方法</strong>，<strong>可序列化</strong>。</p>
</blockquote>
<h2 id="1-2-Spring模块"><a href="#1-2-Spring模块" class="headerlink" title="1.2 Spring模块"></a>1.2 Spring模块</h2><p>Spring是模块化的，可以按需引入。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/2021022317001862.png" alt="Spring模块"></p>
<p>常用模块有：核心容器层Core Container，数据访问层Data Access，Web应用层Web Access。</p>
<h3 id="1-2-1-核心容器层"><a href="#1-2-1-核心容器层" class="headerlink" title="1.2.1 核心容器层"></a>1.2.1 核心容器层</h3><p>主要有 Srping-Beans、Spring-Core、Spring-Context、SpEL等模块组成。</p>
<h4 id="Spring-Beans"><a href="#Spring-Beans" class="headerlink" title="Spring-Beans *"></a>Spring-Beans *</h4><p>基于 <strong>工厂模式</strong> 实现 <strong>对象的创建</strong> 。XML或者注解实现声明式的对象管理。</p>
<h4 id="Spring-Core"><a href="#Spring-Core" class="headerlink" title="Spring-Core *"></a>Spring-Core *</h4><p>Spring<strong>核心功能</strong>实现，包括<strong>控制反转IOC</strong>和<strong>依赖注入DI</strong>。</p>
<p>控制反转模式/思想是通过依赖注入方法来实现的。在某个实例中引用另一个Bean实例的时候，Spring会自动将此实例传入。</p>
<h4 id="Spring-Context"><a href="#Spring-Context" class="headerlink" title="Spring-Context"></a>Spring-Context</h4><p>继承自Spring-Beans，实现国际化、上下文、事件传播、第三方库集成等等功能。</p>
<h4 id="SpEL"><a href="#SpEL" class="headerlink" title="SpEL"></a>SpEL</h4><p>Spring 表达式语言，Spring  Expression Language。</p>
<p>用于在运行过程中查询和操作对象实例。</p>
<h3 id="1-2-2-数据访问层"><a href="#1-2-2-数据访问层" class="headerlink" title="1.2.2 数据访问层"></a>1.2.2 数据访问层</h3><p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210223171500114.png" alt="术语"></p>
<h4 id="1-JDBC"><a href="#1-JDBC" class="headerlink" title="1. JDBC *"></a>1. JDBC *</h4><p>Spring持久化层基于JDBC抽象层实现了在不同数据库之间灵活切换，而不用担心不同数据库之间SQL语法的不兼容。</p>
<h4 id="2-ORM"><a href="#2-ORM" class="headerlink" title="2.ORM *"></a>2.ORM *</h4><p>对象\关系映射。</p>
<p><strong>对象属性与关系型数据库中的字段进行映射。</strong></p>
<p>ORM模块提供了对象关系映射API的集成，包括JPA（Java Persistence API）、JDO（Java DataObject）和Hibernate等。基于该模块，ORM框架能很容易地和Spring的其他功能（例如事务管理）整合。</p>
<h4 id="3-OXM"><a href="#3-OXM" class="headerlink" title="3.OXM"></a>3.OXM</h4><p>OXM模块提供了对OXM实现的支持，比如JAXB、Castor、XML Beans、JiBX、XStream等。</p>
<h4 id="4-JMS"><a href="#4-JMS" class="headerlink" title="4.JMS *"></a>4.JMS *</h4><p>JMS模块包含消息的生产（Produce）和消费（Consume）功能。从Spring 4.1开始，Spring集成了Spring-Messaging模块，用于实现对<strong>消息队列的支持</strong>。</p>
<h4 id="5-事务处理"><a href="#5-事务处理" class="headerlink" title="5. **事务处理 ***"></a>5. **事务处理 ***</h4><p>Spring声明式事务只需要<strong>通过注解或配置</strong>即可实现事务的管理，具体的事务管理工作由<strong>Spring自动处理</strong>，应用程序不需要关心事务的提交（Commit）和回滚（Rollback）。</p>
<h3 id="1-2-3-Web应用层"><a href="#1-2-3-Web应用层" class="headerlink" title="1.2.3 Web应用层"></a>1.2.3 Web应用层</h3><p><strong>Web交互和数据传输功能。</strong></p>
<p>主要包含Web、Web-MVC、Web-Socket、Web-Portlet。</p>
<h4 id="Web"><a href="#Web" class="headerlink" title="Web *"></a>Web *</h4><p>Web应用基本功能，HTTP客户端及Spring远程调用中与Web相关的部分。</p>
<p><strong>Web模块基于Servlet监听器初始化IoC容器。</strong></p>
<h4 id="Web-MVC"><a href="#Web-MVC" class="headerlink" title="Web-MVC *"></a>Web-MVC *</h4><p>Web-MVC模块为Web应用提供了<strong>MVC和REST API服务的实现</strong>。</p>
<p>Spring的MVC框架使数据模型和视图分离，数据模型负责数据的业务逻辑，视图负责数据的展示。</p>
<p>同时，Web-MVC可与Spring框架的其他模块方便地集成。</p>
<h4 id="Web-Socket"><a href="#Web-Socket" class="headerlink" title="Web-Socket"></a>Web-Socket</h4><p>Web-Socket模块提供了对<strong>WebSocket-Base的支持，</strong>用于实现在Web应用程序中<strong>服务端和客户端实时双向通信</strong>，尤其在实时消息推送中应用广泛。</p>
<h4 id="Web-Portlet-没用过"><a href="#Web-Portlet-没用过" class="headerlink" title="Web-Portlet(没用过)"></a>Web-Portlet(没用过)</h4><p>Web-Portlet模块提供了基于Portlet环境的MVC实现，并提供了与Spring Web-MVC模块相关的功能。</p>
<h2 id="1-3核心Jar包"><a href="#1-3核心Jar包" class="headerlink" title="1.3核心Jar包"></a>1.3核心Jar包</h2><p>其实就是上面说的各种模块的Jar包。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210223172309936.png" alt="JAR包1"></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210223172322807.png" alt="JAR包2"></p>
<h2 id="1-4-Spring注解"><a href="#1-4-Spring注解" class="headerlink" title="1.4 Spring注解"></a>1.4 Spring注解</h2><h3 id="1-4-1注解配置"><a href="#1-4-1注解配置" class="headerlink" title="1.4.1注解配置"></a>1.4.1注解配置</h3><p>SpringBoot自动配置，使用XML的就不看了</p>
<h3 id="1-4-2-常用注解"><a href="#1-4-2-常用注解" class="headerlink" title="1.4.2 常用注解"></a>1.4.2 常用注解</h3><p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210224184801412.png" alt="img"></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210224184815705.png" alt="img"></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210224184828461.png" alt="img"></p>
<p>整理一下自己常用的，或者说应该知道的</p>
<table>
<thead>
<tr>
<th>类别</th>
<th>注解</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>Bean声明</td>
<td>@Component</td>
<td>组件，没有明确定义的角色</td>
</tr>
<tr>
<td></td>
<td>@Service</td>
<td>服务</td>
</tr>
<tr>
<td></td>
<td>@Controller</td>
<td>控制器</td>
</tr>
<tr>
<td>Bean注入</td>
<td>@Autowired</td>
<td>服务依赖注入</td>
</tr>
<tr>
<td>配置类注解</td>
<td>@Configuration</td>
<td>声明此类为配置类，包含Value属性可以直接指定属性值</td>
</tr>
<tr>
<td></td>
<td>@Bean</td>
<td>注解在方法上，声明该方法返回值注入容器中</td>
</tr>
<tr>
<td></td>
<td>@ComponentScan</td>
<td>对组件进行扫描</td>
</tr>
<tr>
<td>AOP注解</td>
<td>@Aspect</td>
<td>声明一个切面，使用@After等注解定义通知，可将拦截规则（切点）作为参数</td>
</tr>
<tr>
<td></td>
<td>@After</td>
<td>在方法后执行</td>
</tr>
<tr>
<td></td>
<td>@Before</td>
<td>在方法前执行</td>
</tr>
<tr>
<td></td>
<td>@Around</td>
<td>在方法前和后执行</td>
</tr>
<tr>
<td></td>
<td>@PonitCut</td>
<td>声明切点</td>
</tr>
<tr>
<td>SpringMVC注解</td>
<td>@Controller</td>
<td>控制器</td>
</tr>
<tr>
<td></td>
<td>@RequestMapping</td>
<td>映射Web请求的地址和参数，包括访问路径和参数</td>
</tr>
<tr>
<td></td>
<td>@ResponseBody</td>
<td>可以返回JSON到前端</td>
</tr>
<tr>
<td></td>
<td>@RequestBody</td>
<td>可以将Request参数放入Request Body体中</td>
</tr>
<tr>
<td></td>
<td>@RestController</td>
<td>@Controller和@ResponseBody的结合，可以返回消息的一个Controller</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<h2 id="1-5-IOC原理"><a href="#1-5-IOC原理" class="headerlink" title="1.5 IOC原理"></a>1.5 IOC原理</h2><h3 id="1-5-1-IOC简介"><a href="#1-5-1-IOC简介" class="headerlink" title="1.5.1 IOC简介"></a>1.5.1 IOC简介</h3><p>Spring通过一个配置文件描述Bean和Bean之间的<strong>依赖关系</strong>，利用Java的<strong>反射功能</strong>实例化Bean并建立Bean之间的依赖关系。</p>
<hr>
<p>抽象工厂+反射。</p>
<p>先读取配置文件，后生成实例。</p>
<p>根据类名动态生成对象：<code>f = (类名) class.forName(类名字符串).newInstance()</code> </p>
<h3 id="1-5-2-Bean装配流程"><a href="#1-5-2-Bean装配流程" class="headerlink" title="1.5.2 Bean装配流程"></a>1.5.2 Bean装配流程</h3><ol>
<li>读取配置、注解信息</li>
<li>读取Bean配置信息：Spring在启动时会从XML配置文件或注解中<strong>读取</strong>应用程序提供的Bean<strong>配置信息</strong></li>
<li>并在Spring容器中生成一份相应的<strong>Bean配置注册表</strong>；</li>
<li>然后根据这张注册表<strong>实例化Bean</strong>，装配好Bean之间的依赖关系，为上层业务提供基础的运行环境。</li>
</ol>
<p>其中Bean缓存池为HashMap实现。Spring Bean的装配流程如图。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210224192524135.png" alt="Bean装配流程"></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/19ea23b5b90d631f35d375e20448a519.png" alt="具体流程"></p>
<h3 id="1-5-3-Bean作用域"><a href="#1-5-3-Bean作用域" class="headerlink" title="1.5.3 Bean作用域"></a>1.5.3 Bean作用域</h3><p>五种作用域，分别为：</p>
<ul>
<li>Singleton，单例</li>
<li>Prototype，原型</li>
<li>Request，请求级别</li>
<li>Session，会话级别</li>
<li>Global Session，全局</li>
</ul>
<p>作用域就是用来形容Bean容器中的一个Bean的作用范围。类似于public等修饰符。</p>
<h4 id="1-Singleton"><a href="#1-Singleton" class="headerlink" title="1. Singleton"></a>1. Singleton</h4><p>单例模式。IoC容器中，只会存在一个Bean对象，其他所有Bean引用的依赖都指向这一个Bean。</p>
<p>多线程下不安全。</p>
<p><strong>Spring中默认的就是Singleton作用域。</strong></p>
<h4 id="2-Prototype"><a href="#2-Prototype" class="headerlink" title="2. Prototype"></a>2. Prototype</h4><p>原型模式。</p>
<p><strong>每次通过Bean容器获取</strong>一个Prototype的Bean时，都会创建一个新的实例，每个Bean实例都有<strong>自己的属性和状态</strong>。</p>
<h4 id="3-Request"><a href="#3-Request" class="headerlink" title="3. Request"></a>3. Request</h4><p>HTTP请求范围。</p>
<p><strong>一次HTTP请求</strong>中是同一个Bean，而不同的HTTP请求则是不同的Bean。</p>
<p>当前请求结束后，这个Bean也会被销毁。</p>
<h4 id="4-Session"><a href="#4-Session" class="headerlink" title="4. Session"></a>4. Session</h4><p><strong>一次HTTP Session中</strong>是同一个Bean，仅在当前Session中有效。</p>
<p>不共享数据，Session结束后销毁。</p>
<h4 id="5-Global-Session"><a href="#5-Global-Session" class="headerlink" title="5. Global Session"></a>5. Global Session</h4><p><strong>全局的HTTP Session中</strong>返回同一个Bean。</p>
<p>尽在使用Porlet Context时有效。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/jimsonhappy/article/details/54707694">Connection连接与Session会话的理解</a></p>
<p>通俗来讲，会话(Session) 是通信双方从开始通信到通信结束期间的一个上下文（Context）。这个上下文是一段位于服务器端的内存：记录了本次连接的客户端机器、通过哪个应用程序、哪个用户登录等信息.</p>
<p>连接（Connection）：连接是从客户端到ORACLE实例的一条物理路径。连接可以在网络上建立，或者在本机通过IPC机制建立。通常会在客户端进程与一个专用服务器或一个调度器之间建立连接。</p>
<p>会话(Session) 是和连接(Connection)是同时建立的，两者是对同一件事情不同层次的描述。简单讲，连接(Connection)是物理上的客户端同服务器的通信链路，会话(Session)是逻辑上的用户同服务器的通信交互。</p>
</blockquote>
<h3 id="1-5-4-Bean生命周期"><a href="#1-5-4-Bean生命周期" class="headerlink" title="1.5.4 Bean生命周期"></a>1.5.4 Bean生命周期</h3><p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210224193041984.png" alt="SpringBean生命周期"></p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/riemann_/article/details/118500805">一文读懂 Spring Bean 的生命周期_riemann_的博客-CSDN博客</a></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210710134349143.png" alt="SpringBean生命周期2"></p>
<ul>
<li><p>Bean 自身的方法</p>
<p>比如构造函数、getter/setter 以及 init-method 和 destory-method 所指定的方法等，也就对应着上文说的实例化 -&gt; 属性赋值 -&gt; 初始化 -&gt; 销毁四个阶段。</p>
</li>
<li><p>容器级的方法（BeanPostProcessor 一系列接口）<br>主要是后处理器方法。比如 InstantiationAwareBeanPostProcessor、BeanPostProcessor 接口方法。这些接口的实现类是独立于 Bean 的，并且会注册到 Spring 容器中。在 Spring 容器创建任何 Bean 的时候，这些后处理器都会发生作用。</p>
</li>
<li><p>Bean 级生命周期方法<br>可以理解为 Bean 类直接实现接口的方法，比如 BeanNameAware、BeanFactoryAware、ApplicationContextAware、InitializingBean、DisposableBean 等方法，这些方法只对当前 Bean 生效。</p>
</li>
</ul>
<p>三级方法是一级一级进行扩展的：</p>
<p>首先是最基本的Bean自身方法，进行最基本的创建：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210707002134280.png" alt="Bean自身方法"></p>
<p>之后是容器级处理方法，主要是后置处理方法，在各个阶段前后进行额外的处理：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210707225212729.png" alt="容器级方法扩展"></p>
<p>最后是Bean级方法，只对当前Bean生效，进行额外属性的赋值：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210710134349143.png" alt="SpringBean生命周期2"></p>
<hr>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/e8a473640bcd06e544c86fa729133ac3.png" alt="对应过程"></p>
<hr>
<p>日后需要去看看这个视频讲的不错：<a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1rt4y1v7HD?share_source=copy_web">Spring之Bean的生命周期详解_哔哩哔哩_bilibili</a></p>
<iframe src="//player.bilibili.com/player.html?aid=627385128&bvid=BV1rt4y1v7HD&cid=244295797&page=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>
</blockquote>
<h3 id="1-5-5-四种依赖注入"><a href="#1-5-5-四种依赖注入" class="headerlink" title="1.5.5 四种依赖注入"></a>1.5.5 四种依赖注入</h3><blockquote>
<p>这一块建议阅读<a target="_blank" rel="noopener" href="https://www.zhihu.com/question/23277575/answer/169698662">Spring IoC有什么好处呢？ - 知乎 (zhihu.com)</a>，可以弄清楚到底为啥要用这四种注入方法。</p>
</blockquote>
<ul>
<li>构造器注入</li>
<li>set方法注入</li>
<li>静态工厂注入</li>
<li>实例工厂注入</li>
</ul>
<h4 id="1-构造器注入"><a href="#1-构造器注入" class="headerlink" title="1. 构造器注入"></a>1. 构造器注入</h4><p>构造器注入指通过在类的<strong>构造函数</strong>中注入属性或对象来实现依赖注入。</p>
<p>构造方法传入参数：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//在构造函数中注入message属性</span>
<span class="token keyword">public</span> <span class="token class-name">PersionDaoImpl</span><span class="token punctuation">(</span><span class="token class-name">String</span> message<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
	<span class="token keyword">this</span><span class="token punctuation">.</span>message <span class="token operator">=</span> message<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<p>xml配置文件：</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--定义Bean实例并在构造函数constructor-arg中注入message属性--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>persionDaoImpl<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.PersionDaoImpl<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>constructor-arg</span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>message<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>constructor-arg</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="2-set方法注入"><a href="#2-set方法注入" class="headerlink" title="2. set方法注入"></a>2. set方法注入</h4><p>set方法注入是通过在类中实现<strong>get、set方法</strong>来实现属性或对象的依赖注入的。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">PersionDaoImpl</span><span class="token punctuation">(</span><span class="token class-name">String</span> message<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
	<span class="token keyword">private</span> <span class="token keyword">int</span> id<span class="token punctuation">;</span>	<span class="token comment">//定义属性及其set get方法</span>
	<span class="token keyword">public</span> <span class="token keyword">int</span> <span class="token function">getId</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token keyword">return</span> id<span class="token punctuation">;</span><span class="token punctuation">&#125;</span>
	<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setId</span><span class="token punctuation">(</span><span class="token keyword">int</span> id<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span><span class="token keyword">this</span><span class="token punctuation">.</span>id<span class="token operator">=</span>id<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>xml配置文件</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--定义Bean实例并通过property注入id为123的属性值--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>persionDaoImpl<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.PersionDaoImpl<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>id<span class="token punctuation">"</span></span> <span class="token attr-name">value</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>123<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>property</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-静态工厂注入"><a href="#3-静态工厂注入" class="headerlink" title="3. 静态工厂注入"></a>3. 静态工厂注入</h4><blockquote>
<p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/ceb5ec8f1174">啥是静态工厂方法</a></p>
</blockquote>
<p>静态工厂注入是<strong>通过调用工厂类中定义的静态方法</strong>来获取需要的对象的。</p>
<p>为了让Spring管理所有对象，应用程序<strong>不能直接通过“工厂类.静态方法（）”的方式获取对象，而需要通过Spring注入（XML配置）的方式获取</strong>。代码如下。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">//1.定义静态工厂</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DaoFactory</span><span class="token punctuation">&#123;</span>
	<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">FactoryDao</span> <span class="token function">getStaticFactoryDaoImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
		<span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">StaticFactoryDaoImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">public</span> <span class="token class-name">SpringAction</span><span class="token punctuation">&#123;</span>
		<span class="token comment">//2.定义工厂对象</span>
		<span class="token keyword">private</span> <span class="token class-name">FactoryDao</span> staticFactoryDao<span class="token punctuation">;</span>
		<span class="token comment">//3.注入工厂对象</span>
		<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setStaticFactoryDaoImpl</span><span class="token punctuation">(</span><span class="token class-name">FactoryDao</span> staticFactoryDao<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
			<span class="token keyword">this</span><span class="token punctuation">.</span>staticFactoryDao <span class="token operator">=</span> staticFactoryDao<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上述代码定义了一个<code>DaoFactory</code>工厂类和<code>getStaticFactoryDaoImpl（）</code>静态工厂方法，该方法实例化并返回一个<code>StaticFactoryDaoImpl</code>实例；<br>同时定义了一个SpringAction类，并通过<code>setStaticFactoryDao</code>获取注入的<code>FactoryDao</code>。</p>
<p>具体的XML注入语法如下。</p>
<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token comment">&lt;!--1.定义获取工厂对象的静态方法--></span>
<span class="token comment">&lt;!--factory-method用于指定调用哪个工厂方法--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>staticFactoryDao<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>DaoFactory<span class="token punctuation">"</span></span> <span class="token attr-name">factory-method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getStaticFactoryDaoImpl<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!--2.注入静态工厂实例 --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>springAction<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>SpringAction<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>StaticFactoryDao<span class="token punctuation">"</span></span> <span class="token attr-name">ref</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>staticFactoryDao<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>property</span> <span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上述代码中，第一个bean用来获取工厂及工厂方法，第二个bean用来实际注入。</p>
<h4 id="4-实例工厂注入"><a href="#4-实例工厂注入" class="headerlink" title="4. 实例工厂注入"></a>4. 实例工厂注入</h4><p>实例工厂注入指的是<strong>获取对象实例的方法是非静态的</strong>，因此首先需要实例化一个工厂类对象，然后调用对象的实例化方法来实例化对象。具体代码如下。</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DaoFactory</span><span class="token punctuation">&#123;</span> <span class="token comment">//1.实例工厂</span>
	<span class="token keyword">public</span> <span class="token class-name">FactoryDao</span> <span class="token function">getStaticFactoryDaoImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>  <span class="token comment">//工厂方法不是静态的</span>
		<span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">FactoryDaoImpl</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token keyword">public</span> <span class="token class-name">SpringAction</span><span class="token punctuation">&#123;</span>
		<span class="token keyword">private</span> <span class="token class-name">FactoryDao</span> factoryDao<span class="token punctuation">;</span> <span class="token comment">//2.注入对象</span>
		<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setFactoryDaoImpl</span><span class="token punctuation">(</span><span class="token class-name">FactoryDao</span> factoryDao<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
			<span class="token keyword">this</span><span class="token punctuation">.</span>factoryDao<span class="token operator">=</span> factoryDao<span class="token punctuation">;</span>
		<span class="token punctuation">&#125;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>



<pre class="line-numbers language-xml" data-language="xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>springAction<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>SpringAction<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token comment">&lt;!--1.使用实例工厂的方式注入对象--></span>
    <span class="token comment">&lt;!--ref属性是写的下面的beanName--></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>property</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>factoryDao<span class="token punctuation">"</span></span> <span class="token attr-name">ref</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>factoryDao<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>property</span> <span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!--2.获取对象的方式是从工厂类中获取实例--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>daoFactory<span class="token punctuation">"</span></span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>com.DaoFactory<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span>
<span class="token comment">&lt;!--先实例化工厂类，再从工厂对象中调用工厂方法得到对象--></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>bean</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>factoryDao<span class="token punctuation">"</span></span> <span class="token attr-name">factory-bean</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>daoFactory<span class="token punctuation">"</span></span> <span class="token attr-name">factory-method</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>getFactoryDaoImple<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>bean</span><span class="token punctuation">></span></span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上述代码定义了一个name为factoryDao的工厂类，并通过factory-method定义了实例化对象的方法，这里实例化对象的方法是一个名为getFactoryDaoImpl的方法。该方法返回一个工厂类，在springAction中通过标签注入工厂实例。</p>
<h3 id="1-5-6-自动装配的5种方式"><a href="#1-5-6-自动装配的5种方式" class="headerlink" title="1.5.6 自动装配的5种方式"></a>1.5.6 自动装配的5种方式</h3><ul>
<li>手动装配<ul>
<li>基于XML配置</li>
<li>基于注解</li>
</ul>
</li>
<li>自动装配<ol>
<li>no：不启用自动装配，通过显式设置ref属性来进行对象装配。</li>
<li>byName：通过<strong>参数名</strong>自动装配，<strong>Bean的autowire</strong>被设置为byName后，Spring容器试图匹配并装配与该Bean的属性具有相同名字的Bean。</li>
<li>byType：通过<strong>参数类型</strong>自动装配，<strong>Bean的autowire</strong>被设置为byType后，Spring容器试图匹配并装配与该Bean的属性具有相同类型的Bean。</li>
<li>constructor：通过设置<strong>构造器参数</strong>的方式来装配对象，如果没有匹配到带参数的构造器参数类型，则Spring会抛出异常。</li>
<li>autodetect：<strong>首先尝试</strong>使用constructor来自动装配，如果<strong>无法完成</strong>自动装配，则使用byType方式进行装配。</li>
</ol>
</li>
</ul>
<h2 id="1-6-Spring-AOP原理"><a href="#1-6-Spring-AOP原理" class="headerlink" title="1.6 Spring AOP原理"></a>1.6 Spring AOP原理</h2><h3 id="1-6-1-AOP简介"><a href="#1-6-1-AOP简介" class="headerlink" title="1.6.1 AOP简介"></a>1.6.1 AOP简介</h3><p>AOP，面向切面编程。将公共的与核心业务无关的部分提取出来，<strong>提高代码复用率，降低耦合度。</strong></p>
<ul>
<li>核心关注点：业务核心</li>
<li>横切关注点：公共部分，比如日志、事务、权限认证。</li>
</ul>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210301175351325.png" alt="AOP常见应用场景"></p>
<h3 id="1-6-2-AOP核心概念"><a href="#1-6-2-AOP核心概念" class="headerlink" title="1.6.2 AOP核心概念"></a>1.6.2 AOP核心概念</h3><ul>
<li>切面，Aspect：切面类，在这里面写抽取的额外公共逻辑。</li>
<li>连接点，<strong>JoinPoint</strong>：被拦截的方法，也就是原方法，需要在这前面或者后面执行公共逻辑。</li>
<li>切入点，<strong>Pointcut</strong>：切面中的某个方法，在这前面或者后面执行公共逻辑。@Pointcut注解写切点表达式后跟一个函数，代表原来的方法。</li>
<li>通知，<strong>Advice</strong>：也就是公共逻辑执行的位置，对应Before、After那几个注解。前置通知，后置通知，成功通知，异常通知，环绕通知五类。</li>
<li>目标对象：原来的对象，也就是代理的目标对象。</li>
<li>织入，<strong>weaving</strong> ：将<strong>切面应用</strong>到目标对象并<strong>执行代理对象创建</strong>的过程。</li>
</ul>
<p>这些观念可以结合下面的具体例子来看。</p>
<blockquote>
<h4 id="具体例子：Spring-AOP-SpringBoot集成-柠檬五个半-博客园-cnblogs-com"><a href="#具体例子：Spring-AOP-SpringBoot集成-柠檬五个半-博客园-cnblogs-com" class="headerlink" title="具体例子：Spring AOP SpringBoot集成 - 柠檬五个半 - 博客园 (cnblogs.com)"></a>具体例子：<a target="_blank" rel="noopener" href="https://www.cnblogs.com/LemonFive/p/10983875.html">Spring AOP SpringBoot集成 - 柠檬五个半 - 博客园 (cnblogs.com)</a></h4><p>1.编写业务类：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>example<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>aop</span><span class="token punctuation">;</span>
 
<span class="token comment">/**
* @desc: 核心业务模块
* @author: CSH
**/</span>
<span class="token annotation punctuation">@RestController</span>
<span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span><span class="token string">"/aopController"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">AopController</span> <span class="token punctuation">&#123;</span>
    <span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/Curry"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">Curry</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"库里上场打球了！！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
    
    <span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/Harden"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">Harden</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"哈登上场打球了！！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
 
    <span class="token annotation punctuation">@RequestMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/Durant/&#123;point&#125;"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">Durant</span><span class="token punctuation">(</span><span class="token annotation punctuation">@PathVariable</span><span class="token punctuation">(</span><span class="token string">"point"</span><span class="token punctuation">)</span>  <span class="token keyword">int</span> point<span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"杜兰特上场打球了！！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>2.定义切面类：在类上添加@Aspect 和@Component 注解即可将一个类定义为切面类。 </p>
<ul>
<li><code>@Aspect</code> 注解 使之成为切面类</li>
<li><code>@Component</code> 注解 把切面类加入到IOC容器中</li>
</ul>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>example<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>aop</span><span class="token punctuation">;</span>
 
<span class="token comment">/**
* @desc: 经纪人切面
* @author: CSH
**/</span>
<span class="token annotation punctuation">@Aspect</span>
<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">BrokerAspect</span> <span class="token punctuation">&#123;</span>
 
    <span class="token comment">/**
     * 定义切入点，切入点为com.example.demo.aop.AopController中的所有函数
     *通过@Pointcut注解声明频繁使用的切点表达式
     */</span>
    <span class="token annotation punctuation">@Pointcut</span><span class="token punctuation">(</span><span class="token string">"execution(public * com.example.demo.aop.AopController.*(..)))"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">BrokerAspect</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>
 
    <span class="token comment">/** * @description  在连接点执行之前执行的通知 */</span>
    <span class="token annotation punctuation">@Before</span><span class="token punctuation">(</span><span class="token string">"BrokerAspect()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doBeforeGame</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"经纪人正在处理球星赛前事务！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
 
    <span class="token comment">/** * @description  在连接点执行之后执行的通知（返回通知和异常通知的异常） */</span>
    <span class="token annotation punctuation">@After</span><span class="token punctuation">(</span><span class="token string">"BrokerAspect()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doAfterGame</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"经纪人为球星表现疯狂鼓掌！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
 
    <span class="token comment">/** * @description  在连接点执行之后执行的通知（返回通知） */</span>
    <span class="token annotation punctuation">@AfterReturning</span><span class="token punctuation">(</span><span class="token string">"BrokerAspect()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doAfterReturningGame</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"返回通知：经纪人为球星表现疯狂鼓掌！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
 
    <span class="token comment">/** * @description  在连接点执行之后执行的通知（异常通知） */</span>
    <span class="token annotation punctuation">@AfterThrowing</span><span class="token punctuation">(</span><span class="token string">"BrokerAspect()"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doAfterThrowingGame</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"异常通知：球迷要求退票！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li><code>@Pointcut(&quot;execution(public * com.example.demo.aop.AopController.*(..)))&quot;)</code> ，AOP切点表达式，表示要在哪里切入（在这个方法前后执行切入的函数）<br><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/image-20210804170414308.png" alt="切点表达式"></li>
<li>@Before(“BrokerAspect()”) ：其中的函数名是 <code>@Pointcut</code> 注解之中的，也就是切点之前执行。</li>
<li>@After：在连接点执行之后执行的通知（返回通知和异常通知的异常）</li>
<li>@AfterReturning：在连接点执行之后执行的通知（返回通知）</li>
<li>@AfterThrowing：在连接点执行之后执行的通知（异常通知）</li>
</ul>
<p><strong>可以看到，原业务类无任何更改，只是新写了这么一个Aspect类，就做到了在原方法之前或者之后执行额外方法。所以说做到了低耦合</strong></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/image-20210804172435852.png" alt="输出结果"></p>
<p>最后，Around注解可以在方法前和后执行：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token comment">/** * @description  使用环绕通知 */</span>
<span class="token annotation punctuation">@Around</span><span class="token punctuation">(</span><span class="token string">"BrokerAspect()"</span><span class="token punctuation">)</span>
<span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doAroundGame</span><span class="token punctuation">(</span><span class="token class-name">ProceedingJoinPoint</span> pjp<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Throwable</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">try</span><span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"经纪人正在处理球星赛前事务！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        pjp<span class="token punctuation">.</span><span class="token function">proceed</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"返回通知：经纪人为球星表现疯狂鼓掌！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">catch</span><span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"异常通知：球迷要求退票！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>这里主要是<code>ProceedingJoinPoint pjp</code>这个参数，表示切入点的方法。</p>
<p><code>pjp.proceed();</code>就表示执行原方法，在这一行的前后进行切面逻辑的编写即可。</p>
<p>以及，带参数的方法：</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">package</span> <span class="token namespace">com<span class="token punctuation">.</span>example<span class="token punctuation">.</span>demo<span class="token punctuation">.</span>aop</span><span class="token punctuation">;</span>
<span class="token comment">/**
* @desc:技术统计
* @author: CSH
**/</span>
<span class="token annotation punctuation">@Aspect</span>
<span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">GameDataAspect</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">/**
     * 定义切入点，切入点为com.example.demo.aop.AopController中的所有函数
     *通过@Pointcut注解声明频繁使用的切点表达式
     */</span>
    <span class="token annotation punctuation">@Pointcut</span><span class="token punctuation">(</span><span class="token string">"execution(public * com.example.demo.aop.AopController.Durant(int)) &amp;&amp; args(point))"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token class-name">GameDataAspect</span><span class="token punctuation">(</span><span class="token keyword">int</span> point<span class="token punctuation">)</span><span class="token punctuation">&#123;</span> <span class="token punctuation">&#125;</span>
 
    <span class="token comment">/** * @description  使用环绕通知 */</span>
    <span class="token annotation punctuation">@Around</span><span class="token punctuation">(</span><span class="token string">"GameDataAspect(point)"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">doAroundGameData</span><span class="token punctuation">(</span><span class="token class-name">ProceedingJoinPoint</span> pjp<span class="token punctuation">,</span><span class="token keyword">int</span> point<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Throwable</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">try</span><span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"球星上场前热身！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            pjp<span class="token punctuation">.</span><span class="token function">proceed</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"球星本场得到"</span> <span class="token operator">+</span> point <span class="token operator">+</span> <span class="token string">"分"</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
        <span class="token keyword">catch</span><span class="token punctuation">(</span><span class="token class-name">Throwable</span> e<span class="token punctuation">)</span><span class="token punctuation">&#123;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"异常通知：球迷要求退票！"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>修改切点表达式，传入参数即可。</p>
</blockquote>
<h3 id="1-6-3-AOP代理的两种方式"><a href="#1-6-3-AOP代理的两种方式" class="headerlink" title="1.6.3 AOP代理的两种方式"></a>1.6.3 AOP代理的两种方式</h3><p>两种方式：CGLib动态代理和JDK动态代理。</p>
<p>Spring默认的策略：</p>
<ul>
<li>如果是目标类接口，使用JDK动态代理；</li>
<li>否则使用CGLib动态代理。</li>
</ul>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/NXZp8a3n-ssnC6Y1Hy9lzw">漫画:AOP 面试造火箭事件始末 (qq.com)</a></p>
<p>代理模式。</p>
<p>代理分为静态代理和动态代理：</p>
<ul>
<li>静态代理：就是我们自己手写的，在<strong>编译前定义好</strong>代理类/接口。</li>
<li>动态代理：通过<strong>JDK反射机制</strong>在<strong>程序运行后创建</strong></li>
</ul>
<p>动态代理又分为JDK代理和CGLib代理：</p>
<ul>
<li>JDK动态代理：委托类（原来的目标类）必须<strong>实现接口</strong>，代理类和委托类实现同样的接口，然后代理类对其增强。</li>
<li>CGLib动态代理：委托类不需要实现接口，而是代理类来<strong>继承委托类</strong>。</li>
</ul>
<p>底层源码就先不深挖了。。。</p>
<ul>
<li><p>JDK动态代理通过<strong>反射机制</strong>来实现，有一定的性能问题。</p>
</li>
<li><p>CGLib性能稍高，是通过一个叫<strong>FastClass的机制</strong>来实现的，简单来说就是对类中的方法进行一个索引。</p>
</li>
</ul>
<p>CGLib不能代理 <strong>final 的方法\类</strong>，因为final修饰不能被继承/重写。</p>
</blockquote>
<h3 id="1-6-4-AOP的5种通知类型"><a href="#1-6-4-AOP的5种通知类型" class="headerlink" title="1.6.4 AOP的5种通知类型"></a>1.6.4 AOP的5种通知类型</h3><p>也就是Advice，那几个位置。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210301175940812.png" alt="AOP五种通知类型"></p>
<h3 id="1-6-5-AOP的代码实例"><a href="#1-6-5-AOP的代码实例" class="headerlink" title="1.6.5 AOP的代码实例"></a>1.6.5 AOP的代码实例</h3><p>（上面已经举过例子了）</p>
<p>在Spring中，AOP的使用比较简单，如下代码通过@Aspect注解声明一个切面，通过@Pointcut定义需要拦截的方法，然后用@Before、@AfterReturning、@Around分别实现前置通知、后置通知和环绕通知要执行的方法。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210301180042561.png" alt="AOP实例"></p>
<h2 id="1-7-Spring-MVC原理"><a href="#1-7-Spring-MVC原理" class="headerlink" title="1.7 Spring MVC原理"></a>1.7 Spring MVC原理</h2><p>MVC，模型-视图-控制器。</p>
<p>围绕一个DispatcherServlet，分发请求。</p>
<p><img src="https://img-blog.csdnimg.cn/20210301180234481.png" alt="SpringMVC流程"></p>
<h2 id="1-8-事务"><a href="#1-8-事务" class="headerlink" title="1.8 事务"></a>1.8 事务</h2><p>事务的特性：ACID，原子性，一致性，隔离性，持久性。</p>
<h3 id="1-8-1-本地事务"><a href="#1-8-1-本地事务" class="headerlink" title="1.8.1 本地事务"></a>1.8.1 本地事务</h3><p>JDBC的本地事务：</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210301181354691.png" alt="img"></p>
<h3 id="1-8-2-分布式事务"><a href="#1-8-2-分布式事务" class="headerlink" title="1.8.2 分布式事务"></a>1.8.2 分布式事务</h3><p>跨数据库，分布式事务操作</p>
<ul>
<li>跨数据库<ul>
<li>同一类型数据库，多个数据源</li>
<li>不同数据库</li>
</ul>
</li>
</ul>
<p>Java事务编程接口JTA，和Java事务服务JTS，提供了分布式事务服务。</p>
<ul>
<li>事务管理器：负责所有事务参与单元的协调与控制。</li>
<li>XA协议的资源管理器：XA协议定义了事务管理器与资源管理器之间的接口；资源管理器负责不同数据库具体的事务执行操作。</li>
</ul>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210301182140598.png" alt="UserTransaction操作两个数据库"></p>
<h3 id="1-8-3-两阶段提交协议"><a href="#1-8-3-两阶段提交协议" class="headerlink" title="1.8.3 两阶段提交协议"></a>1.8.3 两阶段提交协议</h3><p>二阶段提交协议，Two-phase Commit，简写为2PC。一般也称为XA方案。</p>
<p><strong>两阶段提交协议用于保证分布式事务的原子性。 即所有数据库，要么都执行要么都不执行。</strong></p>
<p><strong>两个阶段：1.准备阶段；2.提交阶段。</strong></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/20210301182735105.png" alt="两个阶段"></p>
<p>我们需要引入一个<strong>协调者来管理所有的节点</strong>，负责各个本地资源的提交和回滚，并确保这些节点正确提交操作结果，若提交失败则放弃事务。</p>
<p>这里事务管理器是指事务协调者，资源管理器是事务参与者。</p>
<ol>
<li><p>准备阶段</p>
<ol>
<li><p>为每个参与者都发送Prepare消息。</p>
</li>
<li><p>返回消息</p>
<ul>
<li><p>返回失败（例如权限验证不通过）</p>
</li>
<li><p>返回成功：每个参与者在本地执行事务，写本地的undo和redo日志，但不提交，返回成功消息。</p>
</li>
</ul>
</li>
<li><p>等所有参与者都返回结果之后，进入提交阶段。</p>
</li>
</ol>
</li>
<li><p>提交阶段</p>
<ol>
<li>所有的都OK了，那么就提交；</li>
<li>只要有一个不OK或者超时的，就给全部参与者发送回滚消息。</li>
</ol>
</li>
</ol>
<p>事务的执行和释放是<strong>在JPA中基于锁</strong>来实现控制的。</p>
<blockquote>
<p><a target="_blank" rel="noopener" href="https://www.jianshu.com/p/1aa944f44b7b">分布式事务理论-二阶段提交（Two-phase Commit） - 简书 (jianshu.com)</a></p>
<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/35616810">分布式一致性之两阶段提交协议、三阶提交协议 - 知乎 (zhihu.com)</a></p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/9793627-a71a27fddfabfa2b.png" alt="2PC"></p>
<p>同样还有改进的3PC，三阶段提交协议。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/9793627-f90ffe49d3ce34a9.png" alt="三阶段提交协议"></p>
<p>优缺点总结。</p>
<ul>
<li><p>数据不一致问题：</p>
<ul>
<li>只有一部分参与者接收到了提交请求并执行提交操作，但其他未接到提交请求的那部分参与者则无法执行事务提交。于是整个分布式系统便出现了数据不一致的问题。</li>
<li>协调者再发出DoCommit 消息之后宕机，而唯一接收到这条消息的参与者同时也宕机了。那么即使协调者通过选举协议产生了新的协调者，这条事务的状态也是不确定的，没人知道事务是否被已经提交。</li>
</ul>
</li>
<li><p>同步阻塞问题：当本地资源管理器占有临界资源时，其他资源管理器如果要访问同一临界资源，会处于阻塞状态。</p>
</li>
</ul>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/9793627-f61ad7165e8ac269.jpg" alt="优缺点"></p>
</blockquote>
<p>==严重依赖于数据库层面来搞定复杂的事务，效率很低，绝对不适合高并发的场景。==</p>
<p>在微服务中，一般来说某个系统内部如果出现跨多个库的这么一个操作，是不合规的。每个服务只能连自己的库。操作别人的库，必须通过别的服务来接口调用，不能直接操作。</p>
<h2 id="1-9-Mybatis缓存"><a href="#1-9-Mybatis缓存" class="headerlink" title="1.9 Mybatis缓存"></a>1.9 Mybatis缓存</h2><blockquote>
<p><a target="_blank" rel="noopener" href="https://tech.meituan.com/2018/01/19/mybatis-cache.html">聊聊MyBatis缓存机制 - 美团技术团队 (meituan.com)</a><br>美团技术团队NB</p>
</blockquote>
<p>MyBatis缓存分为<strong>一级缓存和二级缓存</strong>。 </p>
<p>一级缓存默认开启，而且是不能被关闭的。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/2021030118292044.png" alt="Mybatis两级缓存"></p>
<h3 id="1-9-1-一级缓存"><a href="#1-9-1-一级缓存" class="headerlink" title="1.9.1 一级缓存"></a>1.9.1 一级缓存</h3><p><strong>缓存到SqlSession中。</strong></p>
<p>缓存的<strong>数据结构是用的Map</strong>，key为MapperId + Offset + Limit + SQL +所有入参。</p>
<p>如果相同SQL的两次查询中间出现了Commit操作（增删改），则会清空SqlSession一级缓存，再重新查询进行缓存。</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/6e38df6a.jpg" alt="一级缓存"></p>
<p>每个SqlSession中持有了Executor，每个Executor中有一个LocalCache。</p>
<h4 id="一级缓存总结"><a href="#一级缓存总结" class="headerlink" title="一级缓存总结"></a>一级缓存总结</h4><ol>
<li>MyBatis一级缓存的<strong>生命周期和SqlSession一致</strong>。</li>
<li>MyBatis一级缓存内部设计简单，<strong>只是一个没有容量限定的HashMap</strong>，在缓存的功能性上有所欠缺。</li>
<li>MyBatis的一级缓存最大范围是SqlSession内部，<strong>有多个SqlSession或者分布式的环境下，数据库写操作会引起脏数据，建议设定缓存级别为Statement。</strong></li>
</ol>
<h3 id="1-9-2-二级缓存"><a href="#1-9-2-二级缓存" class="headerlink" title="1.9.2 二级缓存"></a>1.9.2 二级缓存</h3><blockquote>
<p> 简单来说，二级缓存就是全局变量，一级缓存就是局部变量；不过这里是先全局后局部的。</p>
</blockquote>
<p>二级缓存是可以跨SqlSession的，多个SqlSession共享一个缓存。</p>
<p>进入一级缓存的查询流程前，先在CachingExecutor进行二级缓存的查询</p>
<p><img src="https://gitee.com/songx86/SongPicBed/raw/master/img/28399eba.png" alt="img"></p>
<h4 id="二级缓存总结"><a href="#二级缓存总结" class="headerlink" title="二级缓存总结"></a>二级缓存总结</h4><ol>
<li>MyBatis的二级缓存相对于一级缓存来说，实现了 ** <code>SqlSession</code>之间缓存数据的共享 **，同时粒度更加的细，能够到<code>namespace</code>级别，通过Cache接口实现类不同的组合，对Cache的可控性也更强。</li>
<li>MyBatis<strong>在多表查询时，极大可能会出现脏数据</strong>，有设计上的缺陷，安全使用二级缓存的条件比较苛刻。</li>
<li>在分布式环境下，由于<strong>默认的MyBatis Cache实现都是基于本地的，分布式环境下必然会出现读取到脏数据</strong>，需要<strong>使用集中式缓存将MyBatis的Cache接口实现，有一定的开发成本</strong>，==直接使用Redis、Memcached等分布式缓存可能成本更低，安全性也更高。==</li>
</ol>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">SongX64</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://songx86.gitee.io/article/4bc7a251.html">https://songx86.gitee.io/article/4bc7a251.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">SongX64</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java/">
                                    <span class="chip bg-color">Java</span>
                                </a>
                            
                                <a href="/tags/%E5%90%8E%E7%AB%AF/">
                                    <span class="chip bg-color">后端</span>
                                </a>
                            
                                <a href="/tags/Spring/">
                                    <span class="chip bg-color">Spring</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.jpg" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    
        <style>
    .valine-card {
        margin: 1.5rem auto;
    }

    .valine-card .card-content {
        padding: 20px 20px 5px 20px;
    }

    #vcomments textarea {
        box-sizing: border-box;
        background: url("/medias/comment_bg.png") 100% 100% no-repeat;
    }

    #vcomments p {
        margin: 2px 2px 10px;
        font-size: 1.05rem;
        line-height: 1.78rem;
    }

    #vcomments blockquote p {
        text-indent: 0.2rem;
    }

    #vcomments a {
        padding: 0 2px;
        color: #4cbf30;
        font-weight: 500;
        text-decoration: none;
    }

    #vcomments img {
        max-width: 100%;
        height: auto;
        cursor: pointer;
    }

    #vcomments ol li {
        list-style-type: decimal;
    }

    #vcomments ol,
    ul {
        display: block;
        padding-left: 2em;
        word-spacing: 0.05rem;
    }

    #vcomments ul li,
    ol li {
        display: list-item;
        line-height: 1.8rem;
        font-size: 1rem;
    }

    #vcomments ul li {
        list-style-type: disc;
    }

    #vcomments ul ul li {
        list-style-type: circle;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    #vcomments table, th, td {
        border: 0;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments h1 {
        font-size: 1.85rem;
        font-weight: bold;
        line-height: 2.2rem;
    }

    #vcomments h2 {
        font-size: 1.65rem;
        font-weight: bold;
        line-height: 1.9rem;
    }

    #vcomments h3 {
        font-size: 1.45rem;
        font-weight: bold;
        line-height: 1.7rem;
    }

    #vcomments h4 {
        font-size: 1.25rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    #vcomments h5 {
        font-size: 1.1rem;
        font-weight: bold;
        line-height: 1.4rem;
    }

    #vcomments h6 {
        font-size: 1rem;
        line-height: 1.3rem;
    }

    #vcomments p {
        font-size: 1rem;
        line-height: 1.5rem;
    }

    #vcomments hr {
        margin: 12px 0;
        border: 0;
        border-top: 1px solid #ccc;
    }

    #vcomments blockquote {
        margin: 15px 0;
        border-left: 5px solid #42b983;
        padding: 1rem 0.8rem 0.3rem 0.8rem;
        color: #666;
        background-color: rgba(66, 185, 131, .1);
    }

    #vcomments pre {
        font-family: monospace, monospace;
        padding: 1.2em;
        margin: .5em 0;
        background: #272822;
        overflow: auto;
        border-radius: 0.3em;
        tab-size: 4;
    }

    #vcomments code {
        font-family: monospace, monospace;
        padding: 1px 3px;
        font-size: 0.92rem;
        color: #e96900;
        background-color: #f8f8f8;
        border-radius: 2px;
    }

    #vcomments pre code {
        font-family: monospace, monospace;
        padding: 0;
        color: #e8eaf6;
        background-color: #272822;
    }

    #vcomments pre[class*="language-"] {
        padding: 1.2em;
        margin: .5em 0;
    }

    #vcomments code[class*="language-"],
    pre[class*="language-"] {
        color: #e8eaf6;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }

    #vcomments b,
    strong {
        font-weight: bold;
    }

    #vcomments dfn {
        font-style: italic;
    }

    #vcomments small {
        font-size: 85%;
    }

    #vcomments cite {
        font-style: normal;
    }

    #vcomments mark {
        background-color: #fcf8e3;
        padding: .2em;
    }

    #vcomments table, th, td {
        padding: 12px 13px;
        border: 1px solid #dfe2e5;
    }

    table tr:nth-child(2n), thead {
        background-color: #fafafa;
    }

    #vcomments table th {
        background-color: #f2f2f2;
        min-width: 80px;
    }

    #vcomments table td {
        min-width: 80px;
    }

    #vcomments [type="checkbox"]:not(:checked), [type="checkbox"]:checked {
        position: inherit;
        margin-left: -1.3rem;
        margin-right: 0.4rem;
        margin-top: -1px;
        vertical-align: middle;
        left: unset;
        visibility: visible;
    }
</style>

<div class="card valine-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="vcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/valine/av-min.js"></script>
<script src="/libs/valine/Valine.min.js"></script>
<script>
    new Valine({
        el: '#vcomments',
        appId: 'gRuzkj3uDnUjERvWlFkWkYjF-gzGzoHsz',
        appKey: 'tCCMKQDflcsl0hOAh2CUfvPP',
        notify: 'false' === 'true',
        verify: 'false' === 'true',
        visitor: 'true' === 'true',
        avatar: 'mm',
        pageSize: '10',
        lang: 'zh-cn',
        placeholder: 'just go go'
    });
</script>

<!--酷Q推送-->


    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/article/a815fbe2.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/1/07.jpg" class="responsive-img" alt="20210902神策后端笔试">
                        
                        <span class="card-title">20210902神策后端笔试</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            神策数据后端笔试，还好提前准备了。答案发在这里了代码。不过第二题百思不得其姐。
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-09-02
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E7%AE%97%E6%B3%95/" class="post-category">
                                    算法
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/article/c89a7fbb.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/104.jpg" class="responsive-img" alt="Java常见线程池">
                        
                        <span class="card-title">Java常见线程池</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            主要想说的是常用线程池，手动创建线程池，关于核心线程和工作线程。自己稍微看了一下线程池的源码，理解了一些东西，对上一篇进行补充。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-07-24
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%90%8E%E7%AB%AF/" class="post-category">
                                    后端
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/%E5%90%8E%E7%AB%AF/">
                        <span class="chip bg-color">后端</span>
                    </a>
                    
                    <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/">
                        <span class="chip bg-color">多线程</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="767683882"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">SongX64</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
			<br>
				<a href="https://beian.miit.gov.cn/" target="_blank">鲁ICP备2021015839号-1</a>
				 | 
				<img src="/medias/icp.png" style="vertical-align: text-bottom;" />
		 		<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=37083102000087">鲁公网安备 37083102000087号</a>
            </span>
			
		 
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/SongX64" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:song.x64@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=song-x64@qq.com" class="tooltipped" target="_blank" data-tooltip="QQ联系我: song-x64@qq.com" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
        <div style="position:fixed;bottom:125px;right:16px;cursor: pointer;">
            <a title="兔小巢" target="_blank" rel="noopener" href="https://support.qq.com/products/330452"><i class="fa fa-comments fa-3x"  aria-hidden="true"></i></a>
        </div>
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.5'
        zIndex="-1" count="99"
        src="/libs/background/canvas-nest.js"></script>
    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body>

</html>
